package com.nbsystem.controller;

import com.nbsystem.entity.SysUser;
import com.nbsystem.service.SysUserService;
import com.nbsystem.util.Const;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

@Controller
public class LoginController {
    @Resource
    private SysUserService sysUserService;


    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String login(String userCode, String userPwd, Model model,
                        HttpSession session, HttpServletRequest req, HttpServletResponse resp) throws
            IOException {

        SysUser sysUser = sysUserService.findSysUser(userCode, userPwd);

        String code = req.getParameter("userCode1");
        String code1 = (String) req.getSession().getAttribute
                ("KAPTCHA_SESSION_KEY");
        System.out.println(userCode);
        System.out.println(userPwd);
//        if (sysUser == null){
//            model.addAttribute("msg","用户名或密码不能为空");
//            return "login";
//        }


        if (!Objects.equals(code, code1)) {
            model.addAttribute("msg", "验证码错误，请重新输入");
            return "login";
        }
        if (sysUser != null){
            int id = sysUser.getId();
            SysUser sysUser1 = sysUserService.queryById(id);
            System.out.println("==================================");
            System.out.println(sysUser1);

            session.setAttribute(Const.USERSESSION,sysUser1);
            return "redirect:main";
        }
        model.addAttribute("msg", "账号密码错误，请重新输入");
        return "login";
    }

}
